﻿namespace Sidvall.UI.Entities
{
    public class SelectableKeyValueCollection<TKey, TValue> : BusinessBaseCollection<SelectableKeyValue<TKey, TValue>>
    {
        #region Business Members

        #region SelectedValues

        private System.Collections.ObjectModel.ObservableCollection<TValue> _SelectedValues;
        public System.Collections.ObjectModel.ObservableCollection<TValue> SelectedValues
        {
            get
            {
                if (_SelectedValues == null)
                    this.SelectedValues = new System.Collections.ObjectModel.ObservableCollection<TValue>();
                return _SelectedValues;
            }
            private set
            {
                _SelectedValues = value;
            }
        }

        #endregion

        #region Add

        public void Add(bool isSelected, TKey key, TValue value)
        {
            Add(isSelected, key, value, null);
        }
        public void Add(bool isSelected, TKey key, TValue value, object dataItem)
        {
            var item = new SelectableKeyValue<TKey, TValue>()
            {
                IsSelected = isSelected,
                Key = key,
                Value = value,
                DataItem = dataItem,
            };
            Add(item);
        }

        #endregion

        #endregion
        #region Private Members

        #region InitializeSelectedValues

        private void InitializeSelectedValues()
        {
            var values = new System.Collections.Generic.HashSet<TValue>();
            foreach (var item in this)
            {
                if (item.IsSelected)
                {
                    if (!values.Contains(item.Value))
                        values.Add(item.Value);
                    if (!this.SelectedValues.Contains(item.Value))
                        this.SelectedValues.Add(item.Value);
                }
            }
            var iMax = this.SelectedValues.Count;
            for (int i = iMax - 1; i >= 0; i--)
            {
                var value = this.SelectedValues[i];
                if (!values.Contains(value))
                    this.SelectedValues.Remove(value);
            }
        }

        #endregion

        #endregion
        #region Constructors

        public SelectableKeyValueCollection()
        {
        }

        #endregion
    }
}
